package cedar.sentinel.GWT.client;

import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.DialogBox;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.RootPanel;
import com.google.gwt.user.client.ui.VerticalPanel;

/**
 * Entry point classes define <code>onModuleLoad()</code>.
 */
public class SentinelGWT implements EntryPoint {
	// Enums not supported
	public static int INVALID = 0;
	public static int LEFT_SLOWLY = 1;
	public static int LEFT = 2;
	public static int LEFT_QUICKLY = 3;
	public static int RIGHT_SLOWLY = 4;
	public static int RIGHT = 5;
	public static int RIGHT_QUICKLY = 6;

	/**
	 * The message displayed to the user when the server cannot be reached or
	 * returns an error.
	 */
	private static final String SERVER_ERROR = "An error occurred while "
			+ "attempting to contact the server. Please check your network "
			+ "connection and try again.";

	/**
	 * Create a remote service proxy to talk to the server-side Greeting
	 * service.
	 */
	private final SentinelServiceAsync sentinelService = GWT
			.create(SentinelService.class);

	/**
	 * This is the entry point method.
	 */
	public void onModuleLoad() 
	{
	  final Button stateButton = new Button("Toggle State");
	  final Button connectButton = new Button("Connect");
	  
		final Button leftSlowlyButton = new Button("Left Slowly");
		final Button leftButton = new Button("Left");
		final Button leftQuicklyButton = new Button("Left Quickly");
		
		final Button rightSlowlyButton = new Button("Right Slowly");
		final Button rightButton = new Button("Right");
		final Button rightQuicklyButton = new Button("Right Quickly");

		final Label errorLabel = new Label();

		stateButton.addStyleName("movementButton");
		connectButton.addStyleName("movementButton");
		
		leftSlowlyButton.addStyleName("movementButton");
		leftButton.addStyleName("movementButton");
		leftQuicklyButton.addStyleName("movementButton");
		
		rightSlowlyButton.addStyleName("movementButton");
		rightButton.addStyleName("movementButton");
		rightQuicklyButton.addStyleName("movementButton");

		RootPanel.get("stateButtonContainer").add(stateButton);
		RootPanel.get("stateButtonContainer").add(connectButton);

		RootPanel.get("slowlyButtonContainer").add(leftSlowlyButton);
		RootPanel.get("slowlyButtonContainer").add(rightSlowlyButton);
		
		RootPanel.get("buttonContainer").add(leftButton);
		RootPanel.get("buttonContainer").add(rightButton);
		
		RootPanel.get("quicklyButtonContainer").add(leftQuicklyButton);
		RootPanel.get("quicklyButtonContainer").add(rightQuicklyButton);
		
		RootPanel.get("errorLabelContainer").add(errorLabel);

		// Create the popup dialog box
		final DialogBox dialogBox = new DialogBox();
		dialogBox.setText("Remote Procedure Call");
		dialogBox.setAnimationEnabled(true);
		final Button closeButton = new Button("Close");
		// We can set the id of a widget by accessing its Element
		closeButton.getElement().setId("closeButton");
		final Label textToServerLabel = new Label();
		final HTML serverResponseLabel = new HTML();
		VerticalPanel dialogVPanel = new VerticalPanel();
		dialogVPanel.addStyleName("dialogVPanel");
		dialogVPanel.add(new HTML("<b>Sending name to the server:</b>"));
		dialogVPanel.add(textToServerLabel);
		dialogVPanel.add(new HTML("<br><b>Server replies:</b>"));
		dialogVPanel.add(serverResponseLabel);
		dialogVPanel.setHorizontalAlignment(VerticalPanel.ALIGN_RIGHT);
		dialogVPanel.add(closeButton);
		dialogBox.setWidget(dialogVPanel);

		// Add a handler to close the DialogBox
		closeButton.addClickHandler(new ClickHandler() {
			public void onClick(ClickEvent event) {
				dialogBox.hide();
			}
		});

		// Create a handler for the sendButton and nameField
		class MyHandler implements ClickHandler
		{
			int ID = INVALID;
			
			public MyHandler(int ID)
			{
				this.ID = ID;
			}
			
			/**
			 * Fired when the user clicks on the sendButton.
			 */
			public void onClick(ClickEvent event) 
			{
				sendIDToServer();
			}

			/**
			 * Send the name from the nameField to the server and wait for a response.
			 */
			private void sendIDToServer() 
			{
				errorLabel.setText("");
				textToServerLabel.setText("" +ID);
				serverResponseLabel.setText("");
				sentinelService.sentinelServer("" + ID,
						new AsyncCallback<String>() {
							public void onFailure(Throwable caught) {
								// Show the RPC error message to the user
								dialogBox.setText("Remote Procedure Call - Failure");
								serverResponseLabel.addStyleName("serverResponseLabelError");
								serverResponseLabel.setHTML(SERVER_ERROR);
								dialogBox.center();
								closeButton.setFocus(true);
							}

							public void onSuccess(String result) {
								dialogBox.setText("Remote Procedure Call");
								serverResponseLabel.removeStyleName("serverResponseLabelError");
								serverResponseLabel.setHTML(result);
								dialogBox.center();
								closeButton.setFocus(true);
							}
						});
			}
		}

		class StateHandler implements ClickHandler
		{
      @Override
      public void onClick(ClickEvent event)
      {
        errorLabel.setText("");
        textToServerLabel.setText("s");
        serverResponseLabel.setText("");
        sentinelService.sentinelServer("s",
            new AsyncCallback<String>() {
              public void onFailure(Throwable caught) {
                // Show the RPC error message to the user
                dialogBox.setText("Remote Procedure Call - Failure");
                serverResponseLabel.addStyleName("serverResponseLabelError");
                serverResponseLabel.setHTML(SERVER_ERROR);
                dialogBox.center();
                closeButton.setFocus(true);
              }

              public void onSuccess(String result) {
                dialogBox.setText("Remote Procedure Call");
                serverResponseLabel.removeStyleName("serverResponseLabelError");
                serverResponseLabel.setHTML(result);
                dialogBox.center();
                closeButton.setFocus(true);
              }
            });
      }
		}
		
		
		class QuitHandler implements ClickHandler
		{
			String commandChar;
      @Override
      public void onClick(ClickEvent event)
      {
        errorLabel.setText("");
        if (connectButton.getText() == "Connect")
        {
        	connectButton.setText("Quit");
        	commandChar = "s";
        }
        else
        {
        	connectButton.setText("Connect");
        	commandChar = "q";
        }	
        textToServerLabel.setText(commandChar);
        serverResponseLabel.setText("");
        sentinelService.sentinelServer(commandChar,
            new AsyncCallback<String>() {
              public void onFailure(Throwable caught) {
                // Show the RPC error message to the user
                dialogBox.setText("Remote Procedure Call - Failure");
                serverResponseLabel.addStyleName("serverResponseLabelError");
                serverResponseLabel.setHTML(SERVER_ERROR);
                dialogBox.center();
                closeButton.setFocus(true);
              }

              public void onSuccess(String result) {
                dialogBox.setText("Remote Procedure Call");
                serverResponseLabel.removeStyleName("serverResponseLabelError");
                serverResponseLabel.setHTML(result);
                dialogBox.center();
                closeButton.setFocus(true);
              }
            });
      }
		}
		
		stateButton.addClickHandler(new StateHandler());
		connectButton.addClickHandler(new QuitHandler());
		
		leftSlowlyButton.addClickHandler(new MyHandler(LEFT_SLOWLY));
		leftButton.addClickHandler(new MyHandler(LEFT));
		leftQuicklyButton.addClickHandler(new MyHandler(LEFT_QUICKLY));
		
		rightSlowlyButton.addClickHandler(new MyHandler(RIGHT_SLOWLY));
		rightButton.addClickHandler(new MyHandler(RIGHT));
		rightQuicklyButton.addClickHandler(new MyHandler(RIGHT_QUICKLY));
	}
}
